package com.masterlu.leetcode.daily.linkedlist.simple;

import com.masterlu.leetcode.daily.linkedlist.ListNode;

/**
 * 合并两个有序链表
 * https://leetcode-cn.com/problems/merge-two-sorted-lists/
 *
 * @Author：masterlu
 * @Date：2021/4/6 2:21 下午
 */
public class S21MergeTwoLists {

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {

        //1.链表校验
        if (null == l1) {
            return l2;
        }
        if (null == l2) {
            return l1;
        }
        //2.两个链表元素比较大小拼接
        ListNode newHead = null;
        ListNode curr = newHead;
        while (null != l1 || null != l2) {
            int value = 0;
            int l1val = null == l1 ? 0 : l1.val;
            int l2val = null == l2 ? 0 : l2.val;
            if (l1val <= l2val) {
                value = l1val;
                l1 = l1.next;
            } else {
                value = l2val;
                l2 = l2.next;
            }

            if (newHead == null) {
                newHead = new ListNode(value);
                curr = newHead;
            } else {
                curr.next = new ListNode(value);
                curr = curr.next;
            }
        }
        return newHead;
    }

}
